#!/usr/bin/env python3
# coding:utf-8
#192.168.31.67
import socket
import threading
import time

HOST = '192.168.31.67'
PORT = 10000

current_conn = None
action_list = []

def init_server():
	server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	server.bind((HOST, PORT))
	server.listen(1)
	print("Server successfully created, listening port %s" %(PORT))

	return server

def append_action(action):
	global action_list
	action_list.append(action)

def pop_action():
	global action_list

	if len(action_list) > 0:
		next_action = action_list.pop(0)
		return next_action
	else:
		return None

def process_connection(conn):
	global current_conn
	while True:
		try:
			data = conn.recv(8192)
			if not data:
				conn.close()
				current_conn = None
				break
			append_action(data.decode())

		except Exception as e:
			err = e.args[0]
			if err == 'timed out':
				continue
			else:
				conn.close()
				current_conn = None
				break

def main():
	global current_conn
	server = None

	while True:
		if current_conn:
			time.sleep(1)
			continue
		else:
			server = init_server()
			conn, addr = server.accept()
			server.close()
		current_conn = conn
		threading.Thread(target=process_connection, args=(conn,)).start()


if __name__ == '__main__':
	main()